import { Injectable, signal } from '@angular/core';

export interface Task {
  id: string;
  name: string;
  completed: boolean;
  description?: string;
}

@Injectable({
  providedIn: 'root'
})
export class TasksService {
  private _tasks = signal<Task[]>([]);

  readonly tasks = this._tasks.asReadonly();

  addTask(task: Task) {
    this._tasks.update(tasks => [...tasks, task]);
  }

  updateTask(id: string, updates: Partial<Task>) {
    this._tasks.update(tasks =>
      tasks.map(task =>
        task.id === id ? { ...task, ...updates } : task
      )
    );
  }

  removeTask(id: string) {
    this._tasks.update(tasks => tasks.filter(task => task.id !== id));
  }

  toggleTask(id: string) {
    this._tasks.update(tasks =>
      tasks.map(task =>
        task.id === id ? { ...task, completed: !task.completed } : task
      )
    );
  }

  clearTasks() {
    this._tasks.set([]);
  }
}
